package org.jeecg.modules.flow.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.ObjectUtils;
import org.jeecg.common.api.dto.message.MessageDTO;
import org.jeecg.common.constant.enums.MessageTypeEnum;
import org.jeecg.common.system.vo.DictModel;
import org.jeecg.modules.basic.print.entity.PrintConfig;
import org.jeecg.modules.basic.print.mapper.PrintConfigMapper;
import org.jeecg.modules.flow.record.entity.WmsDocumentTypeStatusReminder;
import org.jeecg.modules.flow.record.entity.WmsFlowRecord;
import org.jeecg.modules.flow.record.service.IWmsDocumentTypeStatusReminderService;
import org.jeecg.modules.flow.record.service.IWmsDocumentTypeStatusUserService;
import org.jeecg.modules.flow.sys.entity.dto.BaseFlowDto;
import org.jeecg.modules.flow.sys.enumx.FlowRecordStatusEnum;
import org.jeecg.modules.system.entity.SysDict;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.mapper.SysDictMapper;
import org.jeecg.modules.system.service.ISysDictService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.system.service.impl.SysBaseApiImpl;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/*
 * 项目名称:    wms-server-jeecg
 * 接口描述:    //
 * 创建人员:    zhaojun
 * 创建时间:    2023-12-04
 */
@Service
@RequiredArgsConstructor
public class DingDingSendMsgService {

    private final PrintConfigMapper printConfigMapper;
    private final IWmsDocumentTypeStatusReminderService wmsDocumentTypeStatusReminderService;
    private final ISysDictService sysDictService;
    private final SysDictMapper sysDictMapper;
    private final DocumentInfoServce documentInfoServce;
    private final IWmsDocumentTypeStatusUserService wmsDocumentTypeStatusUserService;
    private final SysBaseApiImpl sysBaseApi;
    private final ISysUserService sysUserService;


    /**
     * 发送消息
     *
     * @param base
     */
    public void dealInfo(BaseFlowDto base) {
        // 比较当前记录在历史记录中的状态是否发生变化
        List<WmsFlowRecord> flowRecords = base.getFlowRecords();

        boolean dingding = false;
        boolean system = false;

        WmsFlowRecord record = (WmsFlowRecord) base.getDealRecords().get(0);
        Optional<WmsFlowRecord> first = flowRecords.stream().filter(t -> t.getFlowCode().equals(record.getFlowCode())).findFirst();
        if (first.isPresent()) {
            // 流程名称
            String flowName = "";
            WmsDocumentTypeStatusReminder statusReminder = null;
            WmsFlowRecord beforeWmsFlowRecord = first.get();
            if (ObjectUtils.compare(record.getStatus(), beforeWmsFlowRecord.getStatus()) != 0) {
                flowName = FlowRecordStatusEnum.getName(record.getStatus());
                statusReminder = wmsDocumentTypeStatusReminderService.getOne(new LambdaQueryWrapper<WmsDocumentTypeStatusReminder>()
                        .eq(WmsDocumentTypeStatusReminder::getDocumentStatusId, beforeWmsFlowRecord.getFlowId()));
                if (ObjectUtils.isNotEmpty(statusReminder)) {
                    String[] split = statusReminder.getShowMsg().split(",");
                    if (ObjectUtils.compare(Integer.valueOf(split[1]), 1) == 0) {
                        dingding = true;
                    }
                    if (ObjectUtils.compare(Integer.valueOf(split[0]), 1) == 0) {
                        system = true;
                    }
                }
            } else {
                return;
            }

            if (dingding || system) {

                // 业务单据
                String businessType = "";
                // 单据类型
                String documentType = "";
                // 整理发送数据
                PrintConfig printConfig = printConfigMapper.selectById(beforeWmsFlowRecord.getPrintConfigId());

                SysDict sysDict = sysDictMapper.selectOne(new LambdaQueryWrapper<SysDict>().eq(SysDict::getDictCode, printConfig.getBusinessType()));
                if (ObjectUtils.isNotEmpty(sysDict)) {
                    businessType = sysDict.getDictName();
                }
                List<DictModel> dictModels = sysDictService.queryDictItemsByCode(printConfig.getBusinessType());
                Optional<DictModel> first1 = dictModels.stream().filter(t -> t.getValue().equals(printConfig.getDocumentType())).findFirst();
                if (first1.isPresent()) {
                    documentType = first1.get().getValue();
                }

                Map<String, Object> documentInfoMap = documentInfoServce.getDocumentInfo(printConfig.getBusinessType(), base.getInfoId());
                Map<String, Object> data = new HashMap<>();
                data.put("BUSINESSTYPE", businessType);
                data.put("DOCUMENTTYPE", documentType);
                data.put("DOCUMENTCODE", documentInfoMap.get("documentCode"));
                data.put("FLOWNAME", flowName);

                MessageDTO messageDTO = new MessageDTO();

                List<String> toUsers = new ArrayList<>();
                Map<String, List<String>> userCodeMap = wmsDocumentTypeStatusUserService.getUserCode(statusReminder.getId());
                if (CollectionUtils.isNotEmpty(userCodeMap)) {
                    if (CollectionUtils.isNotEmpty(userCodeMap.get("userNames"))) {
                        toUsers.addAll(userCodeMap.get("userNames"));
                    }
                    if (CollectionUtils.isNotEmpty(userCodeMap.get("documentOperators"))) {
                        List<String> list = userCodeMap.get("documentOperators");
                        if (CollectionUtils.isNotEmpty(list)) {
                            Map<String, Object> classMap = (Map<String, Object>) documentInfoMap.get("classMap");
                            List<String> userList = new ArrayList<>();
                            for (String operator : list) {
                                if (ObjectUtils.isNotEmpty(classMap.get(operator))) {
                                    String id = (String) classMap.get(operator);
                                    userList.add(id);
                                }
                            }
                            if (CollectionUtils.isNotEmpty(userList)) {
                                List<SysUser> sysUsers = sysUserService.list(new LambdaQueryWrapper<SysUser>().in(SysUser::getId, userList));
                                if (CollectionUtils.isNotEmpty(sysUsers)) {
                                    List<String> sysUserNames = sysUsers.stream().map(t -> t.getUsername()).collect(Collectors.toList());
                                    toUsers.addAll(sysUserNames);
                                }
                            }
                        }
                    }
                }

                messageDTO.setToUser(String.join(",", toUsers));
                messageDTO.setData(data);
                messageDTO.setTemplateCode(statusReminder.getReminderTemplateCode());
                messageDTO.setTitle("流程信息提示");

                if (dingding) {
                    messageDTO.setType(MessageTypeEnum.XT.getType());
                    sysBaseApi.sendTemplateMessage(messageDTO);
                }

                if (system) {
                    messageDTO.setType(MessageTypeEnum.DD.getType());
                    sysBaseApi.sendTemplateMessage(messageDTO);
                }
            }
        }
    }
}
